#!/usr/bin/python
'''
/*
 * This computer program is the confidential information and proprietary trade
 * secret of VistaraIT LLC.  Possessions and use of this program must  conform
 * strictly to the license agreement between the user and VistaraIT LLC.,  and
 * receipt or possession does not convey any rights to divulge, reproduce,  or
 * allow others to use this program without specific written authorization  of
 * VistaraIT LLC.
 * 
 * Copyright (c) 2014 VistaraIT, Inc. All rights reserved.
 */
'''

from appliance.datetimeinfo import DateTimeInfo
from django import forms
from webutils import WebUtils,RequestUtils
import re

#mm-dd-yyyy format
dateregx = "^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.]((?:19|20)\d\d)$"

class ValidationUtils(object):
    
    def __init__(self):
        self.webutils = WebUtils()
        
    def isNULL(self,value):
        return self.webutils.isNULL(value)
    
    def getDefBridgeNetworkInfo(self, request):
        bridgeNwInfo = {}
        bridgeNwInfo['bridge_ip'] = request.POST.get('bridge_ip')
        bridgeNwInfo['bridge_nm'] = request.POST.get('bridge_nm')
        bridgeNwInfo['bridge_dhcp_start'] = request.POST.get('bridge_dhcp_start')
        bridgeNwInfo['bridge_dhcp_end'] = request.POST.get('bridge_dhcp_end')
        return bridgeNwInfo
    
    def isDefBridgeNetworkInfoValid(self, bridgeNwInfo):
        errors = []
        if self.isValidIP(bridgeNwInfo['bridge_ip']) == False:
            errors.append("Invalid IP Address")
        if self.isValidNetMask(bridgeNwInfo['bridge_nm']) == False:
            errors.append("Invalid Subnet Address")
        if self.isValidIP(bridgeNwInfo['bridge_dhcp_start']) == False:
            errors.append("Invalid DHCP Start Address")
        if self.isValidIP(bridgeNwInfo['bridge_dhcp_end']) == False:
            errors.append("Invalid DHCP End Address")
        return errors

    def getNetworkInfo(self, request):
        networkInfo = {}
        networkInfo['domainname']=request.POST.get('domainname')
        networkInfo['hostname']=request.POST.get('hostname')
        networkInfo['default_iface']=request.POST.get('interface')
        networkInfo['dhcp']=request.POST.get('dhcp', False)
        if networkInfo['dhcp'] == False:
            networkInfo['ipaddr']=request.POST.get('ipaddr')
            networkInfo['subnet']=request.POST.get('subnet')
            networkInfo['gateway']=request.POST.get('gateway')
            networkInfo['dns1']=request.POST.get('dns1')
            networkInfo['dns2']=request.POST.get('dns2')
        networkInfo['enableNativeVlan']=request.POST.get('nativeVlan', False)
        if networkInfo['enableNativeVlan'] != False:
            networkInfo['vlanid']=request.POST.get('vlanid')
        else:
            networkInfo['vlanid'] = ""
        return networkInfo

    def isNetworkInfoValid(self, networkInfo):
        errors = []
        if self.isNULL(networkInfo['hostname']):
            errors.append("Host Name is required.")
        if self.isValidHost(networkInfo['hostname']) == False:
            errors.append("Invalid Host Name.")
        if self.isNULL(networkInfo['domainname']):
            errors.append("Domain Name is required.")
        if self.isValidDomain(networkInfo['domainname']) == False:
            errors.append("Invalid Domain Name.")
        if self.isNULL(networkInfo['default_iface']):
            errors.append("Invalid interface name.")

        if networkInfo['dhcp'] == False:
            if self.isValidIP(networkInfo['ipaddr']) == False:
                errors.append("Invalid IP Address")
            if self.isValidNetMask(networkInfo['subnet']) == False:
                errors.append("Invalid Subnet Address")
            if self.isValidIP(networkInfo['gateway']) == False:
                errors.append("Invalid Gateway Address")
            if self.isGatewayInNetwork(networkInfo['ipaddr'], networkInfo['subnet'], networkInfo['gateway']) == False:
                errors.append("Given gateway is not in network")
            if self.isValidIP(networkInfo['dns1']) == False:
                errors.append("Invalid PrimaryDNS Address")
            if self.isValidIP(networkInfo['dns2']) == False:
                errors.append("Invalid SecondaryDNS Address")
        if networkInfo['enableNativeVlan'] != False:
            if self.isNULL(networkInfo['vlanid']):
                errors.append("Invalid VLAN ID")
            elif self.isValidInteger(networkInfo['vlanid']) == False:
                errors.append("Invalid VLAN ID")
            elif self.isValidInteger(networkInfo['vlanid']) == True and (int(networkInfo['vlanid']) < 0 or int(networkInfo['vlanid']) > 4095):
                errors.append("Invalid VLAN ID")
        
        return errors

    def getStaticRouteInfo(self, request):
        srouteInfo = {}
        srouteInfo['srouteIP'] = request.POST.get('srouteIP')
        srouteInfo['srouteGateway'] = request.POST.get('srouteGateway')
        srouteInfo['srouteSubnet'] = request.POST.get('srouteSubnet')
        srouteInfo['srouteMetric'] = request.POST.get('srouteMetric', 0)
        srouteInfo['srouteInterface'] = request.POST.get('srouteInterface')
        return srouteInfo
    
    def getEditStaticRouteInfo(self, request):
        srouteInfo = {}
        oldsrouteInfo = {}
        srouteInfo['srouteIP'] = request.POST.get('srouteIP')
        srouteInfo['srouteGateway'] = request.POST.get('srouteGateway')
        srouteInfo['srouteSubnet'] = request.POST.get('srouteSubnet')
        srouteInfo['srouteMetric'] = request.POST.get('srouteMetric', 0)
        srouteInfo['srouteInterface'] = request.POST.get('srouteInterface')
        oldsrouteInfo['srouteIP'] = request.POST.get('oldsrouteIP')    
        oldsrouteInfo['srouteGateway'] = request.POST.get('oldsrouteGateway')
        oldsrouteInfo['srouteSubnet'] = request.POST.get('oldsrouteSubnet')
        oldsrouteInfo['srouteMetric'] = request.POST.get('oldsrouteMetric', 0)
        oldsrouteInfo['srouteInterface'] = request.POST.get('oldsrouteInterface')
        return srouteInfo, oldsrouteInfo
    
    def isStaticRouteInfoValid(self, srouteInfo):
        errors = []
        if self.isValidIP(srouteInfo['srouteIP']) == False:
            errors.append("Invalid Network Address")
        if self.isValidNetMask(srouteInfo['srouteSubnet']) == False:
            errors.append("Invalid Subnet Address")
        if self.isValidIP(srouteInfo['srouteGateway']) == False:
            errors.append("Invalid Gateway Address")
        if self.isValidInteger(srouteInfo['srouteMetric']) == False:
            errors.append("Invalid Metric")
        elif self.isValidInteger(srouteInfo['srouteMetric']) == True and int(srouteInfo['srouteMetric']) < 0:
            errors.append("Invalid Metric")
        return errors

    def getVlanInfo(self, request):
        vlanInfo = {}
        vlanInfo['vlanID'] = request.POST.get('vlanID')
        vlanInfo['vlanIP'] = request.POST.get('vlanIP')
        vlanInfo['vlanSubnet'] = request.POST.get('vlanSubnet')
        vlanInfo['vlanInterface'] = request.POST.get('vlanInterface')
        return vlanInfo
    
    def getEditVlanInfo(self, request):
        vlanInfo = {}
        oldvlanInfo = {}
        vlanInfo['vlanID'] = request.POST.get('vlanID')
        vlanInfo['vlanIP'] = request.POST.get('vlanIP')
        vlanInfo['vlanSubnet'] = request.POST.get('vlanSubnet')
        vlanInfo['vlanInterface'] = request.POST.get('vlanInterface')
        oldvlanInfo['vlanID'] = request.POST.get('oldvlanID')
        oldvlanInfo['vlanName'] = request.POST.get('oldvlanName')
        oldvlanInfo['vlanIP'] = request.POST.get('oldvlanIP')
        oldvlanInfo['vlanSubnet'] = request.POST.get('oldvlanSubnet')
        oldvlanInfo['vlanInterface'] = request.POST.get('oldvlanInterface')
        return vlanInfo, oldvlanInfo
    
    def getEditIfaceInfo(self, request):
        ifaceInfo = {}
        oldIfaceInfo = {}
        ifaceInfo['iface'] = request.POST.get('iface')
        ifaceInfo['ip'] = request.POST.get('ifaceIP')
        ifaceInfo['nm'] = request.POST.get('ifaceSubnet')
        oldIfaceInfo['iface'] = request.POST.get('oldIface')
        oldIfaceInfo['ip'] = request.POST.get('oldIfaceIP')
        oldIfaceInfo['nw'] = request.POST.get('oldIfaceSubnet')
        
        return ifaceInfo, oldIfaceInfo
    
    def isVlanInfoValid(self, vlanInfo):
        errors = []
        if self.isValidInteger(vlanInfo['vlanID']) == False:
            errors.append("Invalid Vlan ID")
        elif self.isValidInteger(vlanInfo['vlanID']) == True and (int(vlanInfo['vlanID']) < 0 or int(vlanInfo['vlanID']) > 4095):
            errors.append("Invalid Vlan ID")
        if self.isValidIP(vlanInfo['vlanIP']) == False:
            errors.append("Invalid IP Address")
        if self.isValidNetMask(vlanInfo['vlanSubnet']) == False:
            errors.append("Invalid Subnet Address")
        if vlanInfo['vlanInterface'] == "select":
            errors.append("Invalid Interface.")
        return errors


    def isIfaceInfoValid(self, ifaceInfo):
        errors = []
        if self.isValidIP(ifaceInfo['ip']) == False:
            errors.append("Invalid IP Address")
        if self.isValidNetMask(ifaceInfo['nm']) == False:
            errors.append("Invalid Subnet Address")
        if ifaceInfo['iface'].strip() == "":
            errors.append("Invalid Interface.")
        return errors
    
    def getDateTimeInfo(self,request):
        requestUtils = RequestUtils(request)
        datetimeInfo = DateTimeInfo()
        datetimeInfo.timezone=request.POST.get('timezone')
        datetimeInfo.ntpON= requestUtils.getBooleanParameter('ntpON')
        datetimeInfo.ntpserver1=request.POST.get('ntpserver1')
        datetimeInfo.ntpserver2=request.POST.get('ntpserver2')
        datetimeInfo.setDateTime=requestUtils.getBooleanParameter('setDateTime')
        if datetimeInfo.setDateTime:
            datetimeInfo.hour=requestUtils.getInterger('hour')
            datetimeInfo.min=requestUtils.getInterger('min')
            datetimeInfo.sec=requestUtils.getInterger('sec')
            datetimeInfo.datestr=request.POST.get('datestr')
        return datetimeInfo

    def isDateTimeInfoValid(self,datetimeinfo):
        errors = []
        if self.isNULL(datetimeinfo.timezone):
            errors.append("Timezone is required.")
        if datetimeinfo.ntpON:
            if self.isNULL(datetimeinfo.ntpserver1):
                errors.append("NTP Server1 is required.")
            elif self.isValidIP(datetimeinfo.ntpserver1) == False:
                errors.append("Invalid NTP Server1 Address")
            if self.isNULL(datetimeinfo.ntpserver2):
                errors.append("NTP Server2 is required.")
            elif self.isValidIP(datetimeinfo.ntpserver2) == False:
                errors.append("Invalid NTP Server2 Address")
            
        if datetimeinfo.setDateTime:
            if self.isNULL(datetimeinfo.hour):
                errors.append("Hour value is required.")
            elif self.isValidInteger(datetimeinfo.hour) == False or datetimeinfo.hour < 0 or datetimeinfo.hour > 23:
                errors.append("Invalid hour value")

            if self.isNULL(datetimeinfo.min):
                errors.append("Min value is required.")
            elif self.isValidInteger(datetimeinfo.min) == False or datetimeinfo.min < 0 or datetimeinfo.min > 59:
                errors.append("Invalid min value")

            if self.isNULL(datetimeinfo.sec):
                errors.append("Sec value is required.")
            elif self.isValidInteger(datetimeinfo.sec) == False or datetimeinfo.sec < 0 or datetimeinfo.sec > 59:
                errors.append("Invalid sec value")

            if self.isNULL(datetimeinfo.datestr):
                errors.append("Date value is required.")
            elif re.match(dateregx,datetimeinfo.datestr) == None:
                errors.append("Invalid Date format.")
        return errors

    def isNTPSYNCValid(self,datetimeinfo):
        errors = []
        if datetimeinfo.ntpON:
            if self.isNULL(datetimeinfo.ntpserver1):
                errors.append("NTP Server1 is required.")
            elif self.isValidIP(datetimeinfo.ntpserver1) == False:
                errors.append("Invalid NTP Server1 Address")
            if self.isNULL(datetimeinfo.ntpserver2):
                errors.append("NTP Server2 is required.")
            elif self.isValidIP(datetimeinfo.ntpserver2) == False:
                errors.append("Invalid NTP Server2 Address")
        return errors

    
    def getProxyInfo(self,request):
        form = {}
        form['connection'] = request.POST.get('connection','direct')
        if form['connection'] == 'proxy':
            form['proxy_ip'] = request.POST.get('proxy_ip','')
            form['proxy_port'] = request.POST.get('proxy_port','')
            form['proxy_usr'] = request.POST.get('proxy_usr','')
            form['proxy_pwd'] = request.POST.get('proxy_pwd','')
        return form
    
    def isRegistrationFormValid(self, form):
        errors = []
        try:
            if form['connection'] == 'proxy':
                if self.isNULL(form['proxy_ip']):
                    errors.append("Proxy IP is required")
                elif self.isValidIP(form['proxy_ip']) == False:
                    errors.append("Invalid proxy IP")
                if self.isNULL(form['proxy_port']):
                    errors.append("Proxy port is required")
                elif self.isValidInteger(form['proxy_port']) == False:
                    errors.append("Invalid proxy port")
                elif self.isValidInteger(form['proxy_port']) == True and int(form['proxy_port']) < 0:
                    errors.append("Invalid proxy port")
                elif self.isNULL(form['proxy_usr']) and not self.isNULL(form['proxy_pwd']):
                    errors.append("Proxy user is required if proxy password is given.")
                elif not self.isNULL(form['proxy_usr']) and self.isNULL(form['proxy_pwd']):
                    errors.append("Proxy password is required if proxy user is given.")
        except:
            errors.append("Form validation failed.")
        return errors
    
    def getXMConfig(self,request):
        form = {}
        form['domainName'] = request.POST.get('domainName')
        form['maxMemory'] = request.POST.get('maxMemory')
        form['diskSize'] = request.POST.get('diskSize')
        form['diskPath'] = request.POST.get('diskPath')
        form['diskType'] = request.POST.get('diskType')
        form['isoPath'] = request.POST.get('isoPath')
        form['bootPriority'] = request.POST.get('bootPriority')
        form['onPowerOff'] = request.POST.get('onPowerOff')
        form['onReboot'] = request.POST.get('onReboot')
        form['onCrash'] = request.POST.get('onCrash')
        form['bridgeInterface'] = request.POST.get('bridgeInterface')
        form['autoStart'] = request.POST.get('autoStart')
        return form
    
    def isXMConfigValid(self,form):
        errors = []
        if self.isNULL(form['domainName']):
            errors.append("xm name is required.")
        if self.isNULL(form['maxMemory']):
            errors.append("xm max memory is required.")
        elif self.isValidInteger(form['maxMemory']) == False:
            errors.append("invalid max memory.")
        if self.isNULL(form['diskSize']):
            errors.append("disk size is required.")
        if self.isNULL(form['diskPath']):
            errors.append("invalid disk path.")
        if self.isNULL(form['bootPriority']):
            errors.append("invalid boot priority.")
        if self.isNULL(form['onPowerOff']):
            errors.append("invalid power off option.")
        if self.isNULL(form['onReboot']):
            errors.append("invalid reboot option.")
        if self.isNULL(form['onCrash']):
            errors.append("invalid crash option.")
        if form['bridgeInterface'] == "select":
            errors.append("Invalid Interface.")
        pattern = form['diskType'] + "$"
        match = re.search(pattern, form['diskPath'], re.IGNORECASE)
        if match == None:
            errors.append("invalid disk type.")
        return errors

    def getMACProvisioningInfo(self, request):
        infoHash = {}
        infoHash['controller'] = request.POST.get('controller')
        if infoHash['controller'] == "IPMI Controller":
            infoHash['ipmiaddress'] = request.POST.get('ipmiaddress')
            infoHash['ipmiuser'] = request.POST.get('ipmiuser')
            infoHash['ipmipasswd'] = request.POST.get('ipmipasswd')
        elif infoHash['controller'] == "DELL iDRAC":
            infoHash['idracaddress'] = request.POST.get('idracaddress')
            infoHash['idracuser'] = request.POST.get('idracuser')
            infoHash['idracpasswd'] = request.POST.get('idracpasswd')
        elif infoHash['controller'] == "HP iLO":
            infoHash['iloaddress'] = request.POST.get('iloaddress')
            infoHash['ilouser'] = request.POST.get('ilouser')
            infoHash['ilopasswd'] = request.POST.get('ilopasswd')
        
        infoHash['macaddr'] = request.POST.get('macaddr')
        infoHash['ostemplate'] = request.POST.get('ostemplate')
        infoHash['hostname'] = request.POST.get('hostname')
        infoHash['domainname'] = request.POST.get('domainname')
        infoHash['ipaddr'] = request.POST.get('ipaddr')
        infoHash['subnet'] = request.POST.get('subnet')
        infoHash['dns'] = request.POST.get('dns')
        infoHash['gateway'] = request.POST.get('gateway')
        infoHash['passwd'] = request.POST.get('passwd')
        return infoHash

    def isMACInfoValid(self, infoHash):
        errors = []
        rexp = '([a-fA-F0-9]{2}[:|\-]?){6}'
        if infoHash['controller'] == "IPMI Controller":
            if self.isValidIP(infoHash['ipmiaddress']) == False:
                errors.append("Invalid IPMI Address.")
            if self.isNULL(infoHash['ipmiuser']):
                errors.append("IPMI user is required.")
            if self.isNULL(infoHash['ipmipasswd']):
                errors.append("IPMI password is required.")
        elif infoHash['controller'] == "DELL iDRAC":
            if self.isValidIP(infoHash['idracaddress']) == False:
                errors.append("Invalid DRAC Address.")
            if self.isNULL(infoHash['idracuser']):
                errors.append("DRAC user is required.")
            if self.isNULL(infoHash['idracpasswd']):
                errors.append("DRAC password is required.")
        elif infoHash['controller'] == "HP iLO":
            if self.isValidIP(infoHash['iloaddress']) == False:
                errors.append("Invalid HP iLO Address.")
            if self.isNULL(infoHash['ilouser']):
                errors.append("HP iLO user is required.")
            if self.isNULL(infoHash['ilopasswd']):
                errors.append("HP iLO password is required.")
                
        if self.isNULL(infoHash['ostemplate']) or infoHash['ostemplate'] == "--Select--":
            errors.append("Must select a role template.")
        if self.isNULL(infoHash['macaddr']):
            errors.append("MAC Address is required.")
        if not re.compile(rexp).search(infoHash['macaddr']):
            errors.append("Invalid MAC Address.")
        if self.isNULL(infoHash['hostname']):
            errors.append("Host Name is required.")
        if self.isValidHost(infoHash['hostname']) == False:
            errors.append("Invalid Host Name.")
        if self.isNULL(infoHash['domainname']):
            errors.append("Domain Name is required.")
        if self.isValidDomain(infoHash['domainname']) == False:
            errors.append("Invalid Domain Name.")

        if self.isValidIP(infoHash['ipaddr']) == False:
            errors.append("Invalid IP Address")
        if self.isValidNetMask(infoHash['subnet']) == False:
            errors.append("Invalid Subnet Address")
        if self.isValidIP(infoHash['gateway']) == False:
            errors.append("Invalid Gateway Address")
        if self.isValidIP(infoHash['dns']) == False:
            errors.append("Invalid DNS Address")

        if self.isNULL(infoHash['passwd']):
            errors.append("Root Password is required.")
        return errors

    def getDHCPConfInfo(self, request):
        infoHash = {}
        infoHash['domainname'] = request.POST.get('domainname')
        infoHash['startIP'] = request.POST.get('startIP')
        infoHash['endIP'] = request.POST.get('endIP')
        infoHash['gateway'] = request.POST.get('gateway')
        infoHash['subnet'] = request.POST.get('subnet')
        infoHash['dns1'] = request.POST.get('dns1')
        infoHash['dns2'] = request.POST.get('dns2')
        return infoHash

    def isDHCPInfoValid(self, infoHash):
        errors = []
        if self.isNULL(infoHash['domainname']):
            errors.append("Domain Name is required.")
        if self.isValidDomain(infoHash['domainname']) == False:
            errors.append("Invalid Domain Name.")

        if self.isValidIP(infoHash['startIP']) == False:
            errors.append("Invalid DHCP Start IP Address")
        if self.isValidIP(infoHash['endIP']) == False:
            errors.append("Invalid DHCP End IP Address")
        if self.isValidNetMask(infoHash['subnet']) == False:
            errors.append("Invalid Subnet Address")
        if self.isValidIP(infoHash['gateway']) == False:
            errors.append("Invalid Gateway Address")
        if self.isValidIP(infoHash['dns1']) == False:
            errors.append("Invalid DNS #1 Address")
        if self.isValidIP(infoHash['dns2']) == False:
            errors.append("Invalid DNS #2 Address")
        return errors

    def getPingInfo(self, request):
        pingInfo = {}
        pingInfo['ipaddress'] = request.POST.get('ipaddress')
        pingInfo['pkt_count'] = request.POST.get('packets')
        return pingInfo

    def isPingInfoValid(self, pingInfo):
        errors = []
        if self.isValidIP(pingInfo['ipaddress']) == False and self.isValidDomainName(pingInfo['ipaddress']) == False:
            errors.append("Invalid IP Address/HostName")
        if not pingInfo['pkt_count'].isdigit():
            errors.append("Invalid packet count")
        if int(pingInfo['pkt_count'])>=15:
            errors.append("Packet count should not be greater than 15")
        return errors 

    def getTelInfo(self, request):
        telInfo = {}
        telInfo['ipaddress'] = request.POST.get('ipaddress')
        telInfo['port'] = request.POST.get('port')
        return telInfo
    
    def isTelInfoValid(self, telInfo):
        errors = []
        if self.isValidIP(telInfo['ipaddress']) == False and self.isValidDomainName(telInfo['ipaddress']) ==False:
            errors.append("Invalid IP address/HostName")
        if not telInfo['port'].isdigit():
            errors.append("Invalid Port Number")
        return errors

    def getDnsInfo(self, request):
        dnsInfo = {}
        dnsInfo['ipaddress'] = request.POST.get('ipaddress')
        return dnsInfo

    def isDnsInfoValid(self, dnsInfo):
        errors = []
        if self.isValidIP(dnsInfo['ipaddress']) == False:
            errors.append("Invalid IP address")
        return errors
    
    def getTraceInfo(self, request):
        traceInfo = {}
        traceInfo['ipaddress'] = request.POST.get('ipaddress')
        return traceInfo
    
    def isTraceInfoValid(self,traceInfo):
        errors = []
        if self.isValidIP(traceInfo['ipaddress']) == False and self.isValidDomainName(traceInfo['ipaddress']) == False:
            errors.append("Invalid IP Address/Host name")
        return errors
    
    def getSnmpInfo(self, request):
        snmpInfo = {}
        snmpInfo['ipaddress'] = request.POST.get('ipaddress')
        snmpInfo['oid'] = request.POST.get('oid')
        snmpInfo['port'] = request.POST.get('port')
        snmpInfo['community'] = request.POST.get('community')
        snmpInfo['version'] = request.POST.get('version')
        return snmpInfo
    
    def isSnmpInfoValid(self,snmpInfo):
        errors = []
        if self.isValidIP(snmpInfo['ipaddress']) == False and self.isValidDomainName(snmpInfo['ipaddress']) == False:
            errors.append("Invalid IP address/Hostname")
        if not snmpInfo['port'].isdigit():
            errors.append("Invalid port number")
        return errors
    
    def isValidHostName(self, value):
        try:
            host_re = re.compile(r'^([a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?([a-zA-Z0-9][a-zA-Z0-9\-\.]{0,61}[a-zA-Z0-9])$')
            match = host_re.match(value)
            if match:
                return True
            else:
                return False
        except:
            return False
    
    def isValidDomainName(self,value):
        try:
            domain_re = re.compile(r'^\w+\.\w+\.\w+$')
            match = domain_re.match(value)
            if match:
                return True
            else:
                return False
        except:
            return False

    def ipv4_cidr_to_netmask(self,bits):
        """ Convert CIDR bits to netmask """
        netmask = ''
        for i in range(4):
            if i:
                netmask += '.'
            if bits >= 8:
                netmask += '%d' % (2**8-1)
                bits -= 8
            else:
                netmask += '%d' % (256-2**(8-bits))
                bits = 0
        return netmask
    
    def isValidNetMask(self,netmask):
        return netmask in map(lambda x: self.ipv4_cidr_to_netmask(x), range(1,33))
    
    def isValidIP(self,value):
        try:
            ip = forms.IPAddressField()
            ip.clean(value)
            return True
        except:
            pass
        return False
    
    def isValidHost(self,value):
        try:
            host_re = re.compile(r'^([a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])$')
            match = host_re.match(value)
            if match:
                return True
            else:
                return False
        except:
            pass
        return False
    
    def isGatewayInNetwork(self,ip,netmask,gw):
        ip_int = int(''.join([ '%02x' % int(x) for x in ip.split('.') ]), 16)
        gw_int = int(''.join([ '%02x' % int(x) for x in gw.split('.') ]), 16)
        nw_bits = sum([bin(int(x)).count('1') for x in netmask.split('.')])
        mask = (0xffffffff << (32 - int(nw_bits))) & 0xffffffff
        return (ip_int & mask) == (gw_int & mask)
        
    def isValidDomain(self,value):
        try:
            domain_re = re.compile(r'^([a-zA-Z0-9][a-zA-Z0-9\-\.]{0,61}[a-zA-Z0-9])$')
            match = domain_re.match(value)
            if match:
                return True
            else:
                return False
        except:
            pass
        return False
    
    def isValidInteger(self,value):
        try:
            ip = forms.IntegerField()
            ip.clean(value)
            return True
        except:
            pass
        return False
